﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DriveBeamEditor.Controls.BeamNG;
using DriveBeamEditor.Controls.BeamNG.Controls;
using JBeamLibrary;
using WeifenLuo.WinFormsUI.Docking;

namespace DriveBeamEditor.Forms.Docking
{
    public partial class VehicleContentForm : DockContent
    {
        #region Fields

        private BeamNGMainForm _beamNgForm;

        #endregion

        #region Properties

        public VehicleControl Control
        {
            get { return Controls.OfType<VehicleControl>().FirstOrDefault(); }
            set
            {
                Controls.Clear();
                if (value == null) return;

                Controls.Add(value);
                value.Dock = DockStyle.Fill;
                
                Text = value.ToString();
                Icon = value.Icon;
            }
        }

        public BeamNGMainForm BeamNGForm
        {
            get { return _beamNgForm; }
            private set
            {
                if (_beamNgForm != null)
                    UnregisterParentForm();

                _beamNgForm = value;

                if (value != null)
                    RegisterParentForm();
            }
        }

        #endregion

        #region CTORs

        public VehicleContentForm()
        {
            InitializeComponent();
        }

        public VehicleContentForm(VehicleControl control, BeamNGMainForm beamNgForm)
            : this()
        {
            Control = control;
            BeamNGForm = beamNgForm;
        }

        #endregion

        #region Events

        private void OnSelectedVehicleChanged(object sender, Vehicle vehicle)
        {
            if (Control != null)
                Control.Vehicle = vehicle;
        }

        #endregion

        #region Methods

        private void RegisterParentForm()
        {
            BeamNGForm.SelectedVehicleChanged += OnSelectedVehicleChanged;
        }

        private void UnregisterParentForm()
        {
            BeamNGForm.SelectedVehicleChanged -= OnSelectedVehicleChanged;
        }

        #endregion
    }
}
